<template>
  <el-dialog
    v-model="dialogVisible"
    title="导出指定用户收益"
    width="400px"
    @close="resetForm"
  >
    <el-form ref="serviceForm" :model="form" :rules="rules">
      <el-form-item label="用户列表" prop="userIds">
        <el-select
          v-model="form.userIds"
          placeholder="请选择"
          filterable
          clearable
          multiple
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleConfirm"
        >确定</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { exportUserProfitSelected } from "@/api/adminProfitApi";
import { message } from "@/utils/message";

const dialogVisible = ref(false);
interface Item {
  id: number;
  username: string;
}

defineProps({
  userList: {
    type: Array as PropType<Item[]>,
    default: () => []
  }
});
const emits = defineEmits(["refresh"]);
const form = ref({
  userIds: []
});
const timeParams = ref({
  timeUnit: "day",
  startDate: "",
  endDate: ""
});

// 基础校验规则
const rules: FormRules = {
  userIds: [
    { required: true, message: "请选择用户", trigger: "change", type: "array" }
  ]
};

const serviceForm = ref<FormInstance>();
// 重置表单
const resetForm = () => {
  serviceForm.value?.resetFields();
};
const submitLoading = ref(false);
const handleConfirm = () => {
  serviceForm.value.validate(async valid => {
    if (valid) {
      try {
        submitLoading.value = true;
        const userIds = form.value.userIds.join(",");
        const params = {
          userIds,
          ...timeParams.value
        };
        await exportUserProfitSelected(params);
        message("切换成功", { type: "success" });
        emits("refresh");
        dialogVisible.value = false;
      } finally {
        submitLoading.value = false;
      }
    }
  });
};
const open = (time: {
  timeUnit: string;
  startDate: string;
  endDate: string;
}) => {
  timeParams.value = time;
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>
